package com.imesne.office.excel.write;

import com.imesne.office.excel.exception.OfficeException;
import com.imesne.office.excel.model.ExcelBook;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * Created by liyd on 17/7/4.
 */
public class ExcelWriter {

    private ExcelWriterConfig excelWriterConfig;

    public ExcelWriter(ExcelWriterConfig excelWriterConfig) {
        this.excelWriterConfig = excelWriterConfig;
    }

    /**
     * 写入excel内容到文件
     *
     * @param excelBook excel内容
     * @param file      写入的文件，可以是一个已经存在的excel文件
     */
    public void write(ExcelBook excelBook, File file) {

        try {
            byte[] bytes = null;
            if (this.excelWriterConfig.isAppend() && file.exists()) {
                bytes = FileUtils.readFileToByteArray(file);
            }
            byte[] resultBytes = this.writeBytes(excelBook, bytes);
            FileUtils.writeByteArrayToFile(file, resultBytes);
        } catch (IOException e) {
            throw new OfficeException("写入文件失败", e);
        }
    }

    /**
     * 写入excel内容到bytes
     *
     * @param excelBook excel内容
     * @return
     */
    public byte[] writeBytes(ExcelBook excelBook) {

        return this.writeBytes(excelBook, null);
    }

    /**
     * 写入excel内容到bytes
     *
     * @param excelBook      excel内容
     * @param existFileBytes 已经存在的excel bytes
     * @return
     */
    public byte[] writeBytes(ExcelBook excelBook, byte[] existFileBytes) {

        ExcelBookWriter excelBookWriter = this.excelWriterConfig.getExcelBookWriter();
        Workbook workbook = excelBookWriter.writeExcelBook(excelBook, existFileBytes);

        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            workbook.write(bos);
            return bos.toByteArray();
        } catch (IOException e) {
            throw new OfficeException("写入文件失败", e);
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(workbook);
        }
    }


}
